package com.tanhua.server.intercepter;

import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.domain.User;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.w3c.dom.UserDataHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.logging.Handler;

//拦截器类
public class TokenIntercept extends HandlerInterceptorAdapter {



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1.获取请求头
        String token = request.getHeader("Authorization");

        //2.使用工具类,判断token是否有效
        boolean b = JwtUtils.verifyToken(token);
        //3、如果token失效，返回状态码401，拦截
        if (!b){
            response.setStatus(401);
            return false;
        }
        //4.如果token正常,放行
        Claims claims = JwtUtils.getClaims(token);
        String phone = (String) claims.get("phone");
        Integer id = (Integer) claims.get("id");

        //构造对象,存入Threadlocal
        User user = new User();
        user.setMobile(phone);
        user.setId(Long.valueOf(id));

        //将user注入到线程当中
        UserThreadLocal.set(user);
        return true;

    }
    //清空线程
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
